<?php
declare (strict_types = 1);

namespace app\admin\model;

use app\common\model\Rabc\AdminRoleWithMenus;
use think\db\exception\PDOException;
use think\facade\Db;

/**
 * @mixin \think\Model
 */
class AdminRoles extends \app\common\model\Rabc\AdminRoles
{
    public function add(array $params = [])
    {
        Db::startTrans();
        try {
            $role = $this->create($this->setFilterFields($params));

            // 角色关联菜单
            $this->setRoleMenus($role, $params);

            $this->setError('插入成功!');
            Db::commit();
            return true;
        } catch (PDOException $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    public function edit(array $params = [], array $where = [])
    {
        Db::startTrans();
        try {
            $role_id = intval($params[$this->pk]);
            $this->where($this->pk, $role_id)->update($this->setFilterFields($params));

            // 角色关联菜单
            $this->setRoleMenus($this->detail($role_id), $params);

            $this->setError('更新成功!');
            Db::commit();
            return true;
        } catch (PDOException $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    /**
     * 设置关联角色
     *
     * @param $admin
     * @param $params
     *
     * @return bool
     */
    private function setRoleMenus(object $role, array $params)
    {
        $request_menus = $params['menu_ids'] ?? [];
        $all_menus = empty($request_menus) ? [] : AdminMenus::whereIn('menu_id', $request_menus)->select()->toArray();//当前选中的角色
        $new_all_menus = array_column($all_menus, 'menu_id', 'menu_id');

        $has_menus = $role->menus->toArray(); // 当前已有的菜单权限

        $new_has_menus = array_column($has_menus, 'menu_id', 'menu_id');

        // 管理员与角色关联表
        $roleWithMenu = AdminRoleWithMenus::getInstance();

        /**
         * 添加的菜单
         */
        $add_menus = get_array_diff($new_all_menus, $new_has_menus);
        if ( !empty($add_menus) ) {
            foreach ($add_menus as $menu) {
                $roleWithMenu->create(['role_id' => $role->role_id, 'menu_id' => $menu]);
            }
        }

        /**
         * 要删除的菜单
         */
        $delete_menus = get_array_diff($new_has_menus, $new_all_menus);
        if ( !empty($delete_menus) ) {
            foreach ($delete_menus as $menu){
                $roleWithMenu->where(['role_id' => $role->role_id, 'menu_id' => $menu])->delete();
            }
        }
        return true;
    }
}
